package com.tte.common.controller;

import com.tte.common.model.tenum.ResultCode;
import com.tte.common.utils.file.impl.DownloadUtils;
import com.tte.common.model.vo.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.Objects;

/**
 * FileController
 * @Author: DongWH
 * @Date: 2023/12/1 9:26
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    private static final String UPLOAD_DIR = "D:" + File.separator + "Temp";

    /**
     * 文件上传
     * @param file 文件
     * @param request
     * @return
     */
    @PostMapping(value = "/upload")
    public ResultBean uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return new ResultBean(ResultCode.PARAMETER_EMPTY);
        }

        String fileName = file.getOriginalFilename();
        // 构建上传文件的目标路径
        Path targetPath = Paths.get(UPLOAD_DIR, fileName);
        // 将上传的文件保存到目标路径
        try {
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new ResultBean(ResultCode.OK);

    }

    /**
     * 下载文件
     * @param params
     * @param response
     */
    @RequestMapping("/download")
    public void download(@RequestBody Map<String,Object> params, HttpServletResponse response) {
        // path是指想要下载的文件的路径
        String path = Objects.toString(params.get("path"), "");
        log.info("下载文件地址:{}",path);

        File file = new File(path);
        DownloadUtils.downloadFile(file, response);
    }

    /**
     * 下载文件
     * @param params
     * @param response
     */
    @RequestMapping("/downloadEntity")
    public ResponseEntity<byte[]> downloadEntity(@RequestBody Map<String,Object> params, HttpServletResponse response) {
        // path是指想要下载的文件的路径
        String path = Objects.toString(params.get("path"), "");
        log.info("下载文件地址:{}",path);

        File file = new File(path);
        return DownloadUtils.downloadEntity(file);
    }

    /**
     * 下载文件 (适用于大文件)
     * @param params
     * @param response
     */
    @RequestMapping("/downloadBigFile")
    public void downloadBigFile(@RequestBody Map<String,Object> params, HttpServletResponse response) throws IOException {
        response.reset();
        String path = Objects.toString(params.get("path"), "");
        log.info("下载文件地址:{}",path);

        File file = new File(path);
        DownloadUtils.downloadBigFile(file, response);

    }

    /**
     * 下载文件 (适用于大文件)
     * @param params
     * @param response
     */
    @RequestMapping("/downloadBigFileEntity")
    public ResponseEntity<Resource> downloadBigFileEntity(@RequestBody Map<String,Object> params, HttpServletResponse response) throws IOException {
        response.reset();
        String path = Objects.toString(params.get("path"), "");
        log.info("下载文件地址:{}",path);

        File file = new File(path);
        return DownloadUtils.downloadBigFileEntity(file);

    }

    /**
     * 下载网络文件到本地
     * @param path 下载后的文件路径和名称
     * @param netAddress 文件所在网络地址
     */
    @RequestMapping("/netDownloadLocal")
    public void downloadNet(String netAddress, String path) throws IOException {
        URL url = new URL(netAddress);
        URLConnection conn = url.openConnection();
        InputStream inputStream = conn.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(path);

        int bytesum = 0;
        int byteread;
        byte[] buffer = new byte[1024];
        while ((byteread = inputStream.read(buffer)) != -1) {
            bytesum += byteread;
            System.out.println(bytesum);
            fileOutputStream.write(buffer, 0, byteread);
        }
        fileOutputStream.close();
    }

    /**
     * 网络文件获取到服务器后，经服务器处理后响应给前端
     * @param netAddress 文件所在网络地址
     * @param filename 文件名
     * @param isOnLine 在线打开
     * @param response 下载响应
     */
    @RequestMapping("/netDownLoadNet")
    public void netDownLoadNet(String netAddress, String filename, boolean isOnLine, HttpServletResponse response) throws Exception {

        URL url = new URL(netAddress);
        URLConnection conn = url.openConnection();
        InputStream inputStream = conn.getInputStream();

        response.reset();
        response.setContentType(conn.getContentType());
        if (isOnLine) {
            // 在线打开方式 文件名应该编码成UTF-8
            response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(filename, "UTF-8"));
        } else {
            //纯下载方式 文件名应该编码成UTF-8
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        }

        byte[] buffer = new byte[1024];
        int len;
        OutputStream outputStream = response.getOutputStream();
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
    }


}


